package com.sanpu.kxe.business.main.view;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.contract.UserCenterContract;
import com.sanpu.kxe.business.main.interfaces.ISourceChooseListener;
import com.sanpu.kxe.business.main.presenter.UserCenterPresenter;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.view.ShapeImageView;
import com.sanpu.kxe.jump.eventbus.RefreshNickNameEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.dialog.IconSourceDialog;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.ToastUtil;
import com.yalantis.ucrop.UCrop;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.Bind;

/**
 * Description：个人中心
 * Created by 薛勇军 on 2018/7/10.
 */

public class UserCenterActivity extends BaseTitleActivity implements UserCenterContract.View {

    @Bind(R.id.contain_layout)
    LinearLayout vContainer;
    @Bind(R.id.icon)
    ShapeImageView icon;
    @Bind(R.id.headImgLl)
    LinearLayout headImgLl;

    private IconSourceDialog mIconSourceDialog;

    private UserCenterContract.Presenter mPresenter;

    private Uri imageUri;

    private String cameraDir, cameraPath;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_user_center;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("个人资料");
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (!TextUtils.isEmpty(output.getLevelImagePath())) {
            JKImageLoader.getInstance().displayImage(getContext(),
                    UrlConstants.getBaseUrl() + output.getLevelImagePath(), icon);
        }

        cameraDir = CommonConfig.DIR_APP_CACHE + "/";
        cameraPath = cameraDir + "userHeadPortrait.jpg";

        mPresenter = new UserCenterPresenter(this);
        mPresenter.showView();
    }

    @Override
    protected void setListener() {
        super.setListener();
        headImgLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIconSourceDialog = null;
                mIconSourceDialog = new IconSourceDialog(mContext);
                mIconSourceDialog.setListener(new ISourceChooseListener() {
                    @Override
                    public void pickerClick() {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");//相片类型
                        startActivityForResult(intent, CommonConfig.REQUESTCODE_IMAGE_PICKER);
                    }

                    @Override
                    public void takePhotoClick() {
                        File file = new File(cameraDir);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        PackageManager packageManager = mContext.getPackageManager();
                        if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File f = new File(cameraPath);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                imageUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", f);
                                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            } else {
                                imageUri = Uri.fromFile(f);
                            }
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_IMAGE_CAPTURE);
                        } else {
                            ToastUtil.showTextViewPrompt("当前设备不支持给此应用提供拍照功能，请检查系统权限");
                        }
                    }
                });
            }
        });
    }

    @Override
    public void addContainerView(View view, int index) {
        if (view != null) {
            if (index >= 0) {
                vContainer.addView(view, index);
            } else {
                vContainer.addView(view);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshNickName(RefreshNickNameEvent event) {
        mPresenter.refreshNickName();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConfig.REQUESTCODE_IMAGE_PICKER:
                    Uri selectedImage = data.getData();
                    mPresenter.startUCrop(selectedImage);
                    break;
                case CommonConfig.REQUESTCODE_IMAGE_CAPTURE:
                    mPresenter.startUCrop(imageUri, new File(cameraPath));
                    break;
                case UCrop.REQUEST_CROP:
                    mPresenter.onCompress();
                    break;
            }
        }
    }

    @Override
    public void showHeadImageView(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            JKImageLoader.getInstance().displayImage(getContext(), "file://" + filePath, icon);
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(UserCenterContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
